package org.codeasy.ceutils.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件上传工具类
 * 
 * @author wangchongan
 *
 */
public class UploadFilesUtil {
	
	/**
	 * 把上传上来的临时文件进行保存
	 * 
	 * @param tempFile 临时文件
	 * @param saveDirPath 保存到的路径
	 * @param newFileName 保存的新文件名
	 * @return
	 * @throws Exception
	 */
	public File saveFile(File tempFile, String saveDirPath, String newFileName) throws Exception {
		
		 File dir = new File(saveDirPath);
		 if (!dir.exists()) {
			 //批量创建文件夹
			 dir.mkdirs();
		 }
		 
		 BufferedOutputStream bos = null;
		 BufferedInputStream bis = null;
		 
		 File newFile = new File(dir, newFileName);
		 
		 try {
			 FileInputStream fis = new FileInputStream(tempFile);
			 bis = new BufferedInputStream(fis);
			 
			 FileOutputStream fos = new FileOutputStream(newFile);
			 bos = new BufferedOutputStream(fos);
			 
			 byte[] buf = new byte[4096];
			 
			 int len = -1;
			 
			 while ((len = bis.read(buf)) != -1) {
				 bos.write(buf, 0, len);
			 }
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != bis) {
					bis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			} 
			
			try {
				if (null != bos) {
					bos.flush();
					bos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		 
		return newFile;
	}
	
}
